package com.example.erhuo.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.erhuo.R;
import com.example.erhuo.api.NetAPI;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class AddActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int GET_STORAGE_PERMISSION = 2;
    private EditText editTextDescription;
    private EditText editTextTitle;
    private EditText editTextPrice;
    private Button publishButton;
    private ImageButton addPicButton;
    private ImageView imageView;
    private Bitmap image = null;
    private String imagePath = null;

    private static String TAG = "AddActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
            actionBar.setCustomView(R.layout.title_layout);
            TextView textView = (TextView) actionBar.getCustomView().findViewById(R.id.display_title);
            textView.setText("发布商品");
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowCustomEnabled(true);
        }
        setContentView(R.layout.activity_add);
        imageView = findViewById(R.id.add_image);
        addPicButton = findViewById(R.id.add_button_addpic);
        publishButton = findViewById(R.id.add_publish);
        editTextPrice = findViewById(R.id.add_edit_price);
        editTextTitle = findViewById(R.id.add_edit_title);
        editTextDescription = findViewById(R.id.add_edit_description);
        editTextDescription.setSingleLine(false);
        publishButton.setOnClickListener(this);
        addPicButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add_publish: {
                if (hasEmpty() || image == null || imageView == null) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(AddActivity.this);
                    builder.setTitle("不能为空!");
                    builder.setMessage("请填写全部商品信息");
                    builder.setPositiveButton("好的", null);
                    builder.show();
                    return;
                }
                String price = editTextPrice.getText().toString();
                String title = editTextTitle.getText().toString();
                String description = editTextDescription.getText().toString();
                //todo 发布
                File file = new File(imagePath);
                RequestBody image = RequestBody.create(MediaType.parse("image/jpg"), file);
                RequestBody body = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("goodprice", price)
                        .addFormDataPart("goodname", title)
                        .addFormDataPart("goodcategory", "1")
                        .addFormDataPart("gooddescription", description)
                        .addFormDataPart("image", imagePath, image)
                        .build();
                Callback callback = new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        Log.e(TAG, "发布商品信息失败");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(), "发布失败", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        String information = response.body().string();
                        Log.i(TAG, information);
                        JSONObject json;
                        try {
                            json = new JSONObject(information);
                            String code = json.getString("code");
                            switch (code) {
                                case "200": {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(getApplicationContext(), "发布成功", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                    finishThis();
                                    break;
                                }
                                default: {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(getApplicationContext(), "发布失败", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                };
                NetAPI.postJsonWithToken("api/GoodOper/addGood/", body, callback, MainActivity.token);
                break;
            }
            case R.id.add_button_addpic: {
                if (ContextCompat.checkSelfPermission(AddActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    //没有授权进行权限申请
                    ActivityCompat.requestPermissions(AddActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, GET_STORAGE_PERMISSION);
                } else {
                    pickPhoto();
                    break;
                }
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void finishThis() {
        this.finish();
    }

    private boolean hasEmpty() {
        String price = editTextPrice.getText().toString();
        String title = editTextTitle.getText().toString();
        String description = editTextDescription.getText().toString();
        return price.equals("") || title.equals("") || description.equals("");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1: {
                if (resultCode == RESULT_OK) {
                    try {
                        Uri selectedImage = data.getData();
                        String[] filePathColumn = {MediaStore.Images.Media.DATA};
                        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                        cursor.moveToFirst();
                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        imagePath = cursor.getString(columnIndex);
                        cursor.close();
                        image = BitmapFactory.decodeFile(imagePath);
                        imageView.setImageBitmap(image);
                        Toast.makeText(getApplicationContext(), "上传图片成功", Toast.LENGTH_SHORT).show();
                        Log.i(TAG, "图片大小为：" + image.getAllocationByteCount());
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.e(TAG, "读取相册图片出错");
                    }

                }
                break;
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case GET_STORAGE_PERMISSION:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    pickPhoto();
                } else {
                    pickPhoto();
                    //Toast.makeText(this, "You denied the permission", Toast.LENGTH_SHORT).show();
                }
                break;

        }
    }

    private void pickPhoto() {
        Intent intent = new Intent(
                Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        );
        //intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, 1);
    }
}